﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace PC
{

    sealed class 网络 : 数据
    {

        public HttpWebRequest Request;
        public CookieContainer cContainer = new CookieContainer();

        public string[] 建立连接(string URL, string PostData = "")
        {
            Request = (HttpWebRequest)WebRequest.Create(URL);
            if (PostData != "")
            {
                Request.Method = "POST";//设置PostData
                byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
                Request.ContentType = "application/x-www-form-urlencoded";
                Request.ContentLength = byteArray.Length;
                try
                {
                    Stream dataStreamRequest = Request.GetRequestStream();
                    dataStreamRequest.Write(byteArray, 0, byteArray.Length);
                    dataStreamRequest.Close();
                }
                catch (WebException ex)
                {
                    return new string[] { "错误", ex.Message };
                }
            }
            Request.CookieContainer = cContainer;
            return new string[] { "成功" };
        }

        public string[] 获得cookie()
        {
            string[] 错误代码 = 建立连接("https://its.pku.edu.cn/cas/login", 学生.postData());
            if (错误代码[0] == "错误") return 错误代码;
            HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
            //读取cookie(Request);
            //读取网页(response);
            response.Close();
            return new string[] { "成功" };
            //cContainer.GetCookies(request.RequestUri)[0].Expires = cContainer.GetCookies(request.RequestUri)[1].Expires;
        }

        public string[] 连接(string 连接类型)
        {
            string[] 错误代码 = 获得cookie();
            if (错误代码[0] == "错误") return 错误代码;
            建立连接("https://its.pku.edu.cn/netportal/" + 连接类型);
            HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
            //读取网页(response);
            string 文档 = 分析网页(response);
            response.Close();
            return 返回信息(文档);
        }

        private string 分析网页(HttpWebResponse response)
        {
            Stream dataStreamResponse = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStreamResponse);
            string ResponseFromServer = reader.ReadToEnd();
            reader.Close();
            return ResponseFromServer;
        }

        /// <summary>
        /// 通过获取的网页返回相应信息
        /// </summary>
        /// <returns></returns>
        public string[] 返回信息(string 文档)
        {
            int i = 文档.IndexOf("<!--IPGWCLIENT_START") + 21;
            if (i == 20)//没连上
            {
                return new string[] { "错误", "用户名或者密码错误" };
            }
            int j = 文档.IndexOf("IPGWCLIENT_END-->");
            string Content = 文档.Substring(i, j - i - 1);
            if (Content.Contains("SUCCESS=NO"))//出现了各种问题
            {
                string 原因 = Regex.Match(Content, @"(?<=REASON=).*").Value;
                switch (原因)
                {
                    case "当前连接数超过预定值":
                        return 获得IP(文档);
                    default://不是当前的原因
                        return new string[] { "错误", 原因 };
                }
            }
            else
            {
                return 信息翻译(Content);
            }
        }
        /// <summary>
        /// 获得两个链接的IP地址
        /// </summary>
        public string[] 获得IP(string 文档)
        {
            string postData;
            int i = 文档.IndexOf("\"messages\" value") + 18;
            int j = 文档.IndexOf("\">", i);
            学生.value = 文档.Substring(i, j - i);

            postData = "messages=" + 学生.value + "&operation=get_disconnectip_err&from=cas&uid=" + 学生.学号 + "&timeout=1&range=2";

            建立连接("https://its.pku.edu.cn/netportal/ipgw.ipgw?" + postData);//POST不行GET却可以
            HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
            string IP地址 = 分析网页(response);
            response.Close();

            //断开指定连接
            
            Regex[] reg = new Regex[2];
            reg[0] = new Regex(@"(?<=td2>)\d+(\.\d+){3}?");//IP地址
            reg[1] = new Regex(@"(?<=td2>)[\d\-]+\s[\d:]+\.0");//时间
            MatchCollection[] MC = new MatchCollection[2];
            for (i = 0; i < 2; i++) MC[i] = reg[i].Matches(IP地址);
            string[] IP = new string[2 * MC[0].Count];
            //if (MC.Count < 2) return new string[] { "错误", "已打开2个网络链接, 没找到两个IP地址, 请尝试断开所有链接" };
            for (i = 0; i < MC[0].Count; i++)
            {
                IP[i * 2] = MC[0][i].Value;
                IP[i * 2 + 1] = MC[1][i].Value;
            }

            DateTime 时间;
            for (i = 0; i < MC[0].Count; i++)
            {
                时间 = Convert.ToDateTime(IP[2 * i + 1]);
                IP[2 * i + 1] = 时间.ToString("M-d H:mm:ss");
            }
            return IP;


        }

        public string[] 断开指定连接(string IP)
        {
            //断开第一个连接
            string postData = "messages=" + 学生.value + "&operation=disconnectip_err&from=cas&uid=" + 学生.学号 + "&timeout=1&range=1&disconnectip=" + IP;
            建立连接("http://its.pku.edu.cn/netportal/ipgw.ipgw?" + postData);

            HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
            string 文档 = 分析网页(response);
            response.Close();
            string[] Content = 返回信息(文档);
            return Content;
        }

        /// <summary>
        /// 将成功后的信息从英文翻译成中文
        /// </summary>
        /// <param name="Content">从"&lt;--IPGWCLIENT_START"到"IPGWCLIENT_END-->"的部分</param>
        /// <returns></returns>
        private string[] 信息翻译(string Content)
        {
            Content = Content.Replace("STATE=", "状态\t\t");
            Content = Content.Replace("connected", "已连接");
            Content = Content.Replace("USERNAME=", "用户名\t\t");
            Content = Regex.Replace(Content, @"FIXRATE=\S*\s", "");
            Content = Content.Replace("FR_DESC_CN=", "包月状态\t");
            Content = Regex.Replace(Content, @"FR_DESC_EN=\S*\s", "");
            Content = Content.Replace("FR_TIME=", "包月剩余时长\t");
            Match 时长 = Regex.Match(Content, @"(?<=包月剩余时长\t)[\d\.]*(?=小时\s)");
            if (时长.Length > 0)
            {
                TimeSpan 时长_time = TimeSpan.FromHours(Convert.ToDouble(时长.Value));
                string 时长_改 = Convert.ToString((int)时长_time.TotalHours) + "时" + 时长_time.Minutes.ToString() + "分";
                Content = Content.Replace(时长.Value + "小时", 时长_改);
            }

            Content = Content.Replace("SCOPE=", "访问范围\t");
            if (Content.Contains("domestic")) Content = Content.Replace("domestic", "免费流量");
            else Content = Content.Replace("international", "收费流量");
            Content = Content.Replace("CONNECTIONS=", "当前连接数\t");
            Content = Content.Replace("BALANCE=", "余额\t\t");
            Content = Content.Replace("IP=", "IP地址\t\t");
            Content = Content.Replace("MESSAGE=", "信息\t\t");
            return Content.Split(' ');

        }
        private void 读取cookie(HttpWebRequest request)
        {
            //读取cookie
            foreach (Cookie cook in cContainer.GetCookies(request.RequestUri))
            {
                Console.WriteLine("Cookie:");
                Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
                Console.WriteLine("Domain: {0}", cook.Domain);
                Console.WriteLine("Path: {0}", cook.Path);
                Console.WriteLine("Port: {0}", cook.Port);
                Console.WriteLine("Secure: {0}", cook.Secure);

                Console.WriteLine("When issued: {0}", cook.TimeStamp);
                Console.WriteLine("Expires: {0} (expired? {1})", cook.Expires, cook.Expired);
                Console.WriteLine("Don't save: {0}", cook.Discard);
                Console.WriteLine("Comment: {0}", cook.Comment);
                Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
                Console.WriteLine("Version: RFC {0}", cook.Version == 1 ? "2109" : "2965");

                // Show the string representation of the cookie.
                Console.WriteLine("String: {0}", cook.ToString());
            }
        }
        private void 读取网页(HttpWebResponse response)
        {
            //读取文件
            Stream dataStreamResponse = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStreamResponse);
            string ResponseFromServer = reader.ReadToEnd();
            Console.WriteLine(ResponseFromServer);
            reader.Close();
        }



    }
    class 数据
    {
        public struct 用户信息
        {
            public string 学号 { set; get; }
            public string 密码 { set; get; }
            private static fwrd 类型 = fwrd.free;
            public string value;//断开指定连接用
            private static string code = "|;kiDrqvfi7d$v0p5Fg72Vwbv2;|";//固定字符串
            public string postData() { return "fwrd=" + 类型 + "&username1=" + 学号 + "&password=" + 密码 + "&username=" + 学号 + code + 密码 + code + (short)类型; }//组合出的POST表单内容
        }
        private enum fwrd : short
        {
            fee = 11,
            free = 12,
            pkuwireless = 14
        }
        public 用户信息 学生;
    }

}
